<template>
  <div class="wx-users-container">
    <div class="table-operations">
      <a-row :gutter="16">
        <a-col :span="8">
          <a-input-search
            v-model:value="searchParam.keyword"
            placeholder="搜索用户名/昵称"
            @search="onSearch"
            allow-clear
            enter-button
          />
        </a-col>
        <a-col :span="4">
          <a-select
            v-model:value="searchParam.diabetesType"
            placeholder="糖尿病类型"
            style="width: 100%"
            @change="onSearch"
            allow-clear
          >
            <a-select-option :value="1">1型糖尿病</a-select-option>
            <a-select-option :value="2">2型糖尿病</a-select-option>
            <a-select-option :value="3">妊娠糖尿病</a-select-option>
            <a-select-option :value="4">其他类型</a-select-option>
          </a-select>
        </a-col>
        <a-col :span="4">
          <a-select
            v-model:value="searchParam.status"
            placeholder="用户状态"
            style="width: 100%"
            @change="onSearch"
            allow-clear
          >
            <a-select-option :value="1">正常</a-select-option>
            <a-select-option :value="0">禁用</a-select-option>
          </a-select>
        </a-col>
        <a-col :span="8" class="text-right">
          <a-button type="primary" @click="exportUserData">
            <download-outlined />
            导出用户数据
          </a-button>
        </a-col>
      </a-row>
    </div>

    <a-table
      :columns="columns"
      :data-source="userList"
      :pagination="pagination"
      :loading="loading"
      @change="handleTableChange"
      row-key="id"
      size="middle"
      bordered
    >
      <template #bodyCell="{ column, text, record }">
        <template v-if="column.dataIndex === 'avatar'">
          <a-avatar :src="text" alt="头像" />
        </template>
        
        <template v-if="column.dataIndex === 'gender'">
          {{ genderMap[text] }}
        </template>
        
        <template v-if="column.dataIndex === 'diabetesType'">
          {{ diabetesTypeMap[text] || '未知' }}
        </template>
        
        <template v-if="column.dataIndex === 'status'">
          <a-tag :color="text ? 'green' : 'red'">
            {{ text ? '正常' : '禁用' }}
          </a-tag>
        </template>
        
        <template v-if="column.dataIndex === 'createTime'">
          {{ formatDate(text) }}
        </template>
        
        <template v-if="column.dataIndex === 'action'">
          <a-space>
            <a @click="viewUserDetails(record)">查看</a>
            <a-divider type="vertical" />
            <a-switch 
              :checked="record.status === 1" 
              @change="(checked) => toggleUserStatus(record, checked)"
              :checkedChildren="'启用'" 
              :unCheckedChildren="'禁用'"
            />
          </a-space>
        </template>
      </template>
    </a-table>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import { DownloadOutlined } from '@ant-design/icons-vue';
import axios from 'axios';

const router = useRouter();
const loading = ref(false);
const userList = ref([]);

// 表格列定义
const columns = [
  {
    title: '用户ID',
    dataIndex: 'id',
    width: 80
  },
  {
    title: '头像',
    dataIndex: 'avatar',
    width: 80
  },
  {
    title: '用户名',
    dataIndex: 'username',
    ellipsis: true
  },
  {
    title: '昵称',
    dataIndex: 'nickname',
    ellipsis: true
  },
  {
    title: '性别',
    dataIndex: 'gender',
    width: 80
  },
  {
    title: '年龄',
    dataIndex: 'age',
    width: 80
  },
  {
    title: '糖尿病类型',
    dataIndex: 'diabetesType',
    width: 120
  },
  {
    title: '状态',
    dataIndex: 'status',
    width: 100
  },
  {
    title: '注册时间',
    dataIndex: 'createTime',
    width: 180
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: 150
  }
];

// 枚举映射
const genderMap = {
  1: '男',
  2: '女',
  0: '未知'
};

const diabetesTypeMap = {
  1: '1型糖尿病',
  2: '2型糖尿病',
  3: '妊娠糖尿病',
  4: '其他类型'
};

// 搜索参数
const searchParam = reactive({
  keyword: '',
  diabetesType: undefined,
  status: undefined,
  page: 1,
  size: 10
});

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total) => `共 ${total} 条记录`
});

// 获取用户列表
const fetchUserList = async () => {
  try {
    loading.value = true;
    const params = {
      ...searchParam
    };
    
    const response = await axios.get('/admin/api/users/wx-users', { params });
    
    if (response.data.code === 0) {
      userList.value = response.data.data;
      pagination.total = response.data.total || userList.value.length;
    } else {
      message.error(response.data.message || '获取用户列表失败');
    }
  } catch (error) {
    console.error('获取用户列表错误', error);
    message.error('获取用户列表失败');
  } finally {
    loading.value = false;
  }
};

// 搜索
const onSearch = () => {
  searchParam.page = 1;
  fetchUserList();
};

// 表格变化处理
const handleTableChange = (pag) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  searchParam.page = pag.current;
  searchParam.size = pag.pageSize;
  fetchUserList();
};

// 查看用户详情
const viewUserDetails = (record) => {
  router.push(`/wx-user-detail/${record.id}`);
};

// 切换用户状态
const toggleUserStatus = async (record, checked) => {
  try {
    const response = await axios.put(`/admin/api/users/wx-users/${record.id}/status`, {
      status: checked ? 1 : 0
    });
    
    if (response.data.code === 0) {
      message.success(`用户已${checked ? '启用' : '禁用'}`);
      // 更新当前列表项
      record.status = checked ? 1 : 0;
    } else {
      message.error(response.data.message || '操作失败');
    }
  } catch (error) {
    console.error('修改用户状态错误', error);
    message.error('操作失败');
  }
};

// 导出用户数据
const exportUserData = () => {
  const params = {
    keyword: searchParam.keyword || undefined,
    diabetesType: searchParam.diabetesType || undefined,
    status: searchParam.status || undefined
  };
  
  // 构建查询字符串
  const queryString = Object.entries(params)
    .filter(([_, value]) => value !== undefined)
    .map(([key, value]) => `${key}=${value}`)
    .join('&');
  
  // 创建下载链接
  const downloadUrl = `/admin/api/users/export${queryString ? `?${queryString}` : ''}`;
  
  // 创建一个隐藏的a标签来下载文件
  const a = document.createElement('a');
  a.style.display = 'none';
  a.href = downloadUrl;
  a.download = `微信用户数据_${new Date().toISOString().slice(0, 10)}.xlsx`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
};

// 日期格式化
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
};

onMounted(() => {
  fetchUserList();
});
</script>

<style scoped>
.wx-users-container {
  background: #fff;
  padding: 16px;
}

.table-operations {
  margin-bottom: 16px;
}

.text-right {
  text-align: right;
}
</style> 